//
//  OrderForGoodsViewController.m
//  MagazineShangejie
//
//  Created by cnbizMedia on 16/4/26.
//  Copyright © 2016年 CnbizMedia. All rights reserved.
//

#import "OrderForGoodsViewController.h"
#import "LocationListViewController.h"
#import "Util.h"
#import "PayTheVIPViewController.h"
@implementation OrderForGoodsViewController{
 
    
    __weak IBOutlet UILabel *nameAndPhoneNumberLabel;
    
    __weak IBOutlet UILabel *placeLabel;
    
    __weak IBOutlet UILabel *setAPlace;
    
    
    
    __weak IBOutlet UIImageView *goodsImage;
    
    __weak IBOutlet UILabel *goodsNameLabel;
    
    __weak IBOutlet UILabel *goodsModeLabel;
    
    __weak IBOutlet UILabel *goodsMoneyLabel;
    
    __weak IBOutlet UILabel *goodsNumberLabel;
    
    __weak IBOutlet UILabel *goodsNumberLabel1;
    
    __weak IBOutlet UILabel *goodsMoneyLabel1;
    
    __weak IBOutlet UILabel *FreightLabel;
    
    __weak IBOutlet UILabel *total;
    
    
    
    
    
    
    NSInteger intGoodsNumber;
    NSInteger goodsMoney;
    NSInteger FreightMoney;
    NSInteger totalMoney;
    
    NSMutableArray *placeData;
    
    NSMutableDictionary *goodsDic;
    
    BOOL havePlace;
    
    NSInteger placeId;
    
    
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
    
    [self getThePlace];
    
}

-(void)viewDidLoad{
    [super viewDidLoad];
    [self getThePlace];
    
    goodsDic = [UserDefaults objectForKey:@"goodsDic"];
    
    placeData = [[NSMutableArray alloc]init];
    
    intGoodsNumber =  [[UserDefaults objectForKey:@"goodsNumber"] integerValue];
    
    goodsMoney = [goodsDic[@"discount_price"] integerValue];
    if (goodsMoney == 0) {
        goodsMoney = [goodsDic[@"price"] integerValue];
    }
    
    FreightMoney = [goodsDic[@"shipping_base_fee"] integerValue];
    
    
    [goodsImage sd_setImageWithURL:[NSURL URLWithString:goodsDic[@"pic"][0]] placeholderImage:[UIImage imageNamed:@"icon_default_ipad"]];
    
    goodsMoneyLabel.text =[NSString stringWithFormat:@"￥%ld",(long)goodsMoney ];
    goodsMoneyLabel1.text =[NSString stringWithFormat:@"￥%ld",(long)goodsMoney ];
    FreightLabel.text = [NSString stringWithFormat:@"￥%ld",(long)FreightMoney];
    
    goodsNameLabel.text = goodsDic[@"name"];
    
    
    
    goodsNumberLabel1.text = [NSString stringWithFormat:@"%ld",(long)intGoodsNumber] ;
    goodsNumberLabel.text = [NSString stringWithFormat:@"×%@",goodsNumberLabel1.text] ;
    total.text = [NSString stringWithFormat:@"￥%ld",goodsMoney *intGoodsNumber + FreightMoney];
    totalMoney = goodsMoney *intGoodsNumber + FreightMoney;
    
    havePlace = NO;
}

//获取默认地址信息
-(void)getThePlace{

    
    
    [[AppAPIClient sharedClient] GET:@"Shop/ListAddress" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSMutableArray *result = responseObject[@"data"];
        NSLog(@"luntan-data == %@",result);
        if([result isKindOfClass:[NSNull class]]  ){
            return;
        }
        if( [result count] == 0 ){
            return;
        }
        
//            placeData = [[NSMutableArray alloc]initWithArray:responseObject[@"data"] copyItems:YES];
        placeData = responseObject[@"data"];
        
        for ( NSDictionary *aPlace in placeData ) {
            if ([aPlace [@"status"] isEqualToString:@"1"]) {
                nameAndPhoneNumberLabel.text = [NSString stringWithFormat:@"%@      %@", aPlace[@"consignee"] ,aPlace[@"mobile"]];
                placeLabel.text = aPlace[@"full_address"];
                
                placeId = [aPlace[@"id"]integerValue];
                NSLog(@"placeId    %ld",(long)placeId);
                setAPlace.hidden = YES;
                havePlace = YES;
            }
        }
       
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"ERR: %@",operation.responseString);
        [SVProgressHUD dismiss];
 
    }];

    
    
   
}


- (IBAction)addGoodsNumber:(id)sender {
    
    if (intGoodsNumber == [goodsDic[@"num"] integerValue]) {
        return;
    }
    
    goodsNumberLabel1.text = [NSString stringWithFormat:@"%ld",(long)++intGoodsNumber] ;
    goodsNumberLabel.text = [NSString stringWithFormat:@"×%@",goodsNumberLabel1.text] ;
    
    total.text = [NSString stringWithFormat:@"￥%ld",goodsMoney *intGoodsNumber + FreightMoney];
    totalMoney = goodsMoney *intGoodsNumber + FreightMoney;
}

- (IBAction)minusGoodsNumber:(id)sender {
    if (intGoodsNumber > 1) {
        goodsNumberLabel1.text = [NSString stringWithFormat:@"%ld",(long)--intGoodsNumber] ;
        goodsNumberLabel.text = [NSString stringWithFormat:@"×%@",goodsNumberLabel1.text] ;
        total.text = [NSString stringWithFormat:@"￥%ld",goodsMoney *intGoodsNumber + FreightMoney];
        totalMoney = goodsMoney *intGoodsNumber + FreightMoney;
    }
}


- (IBAction)pushTheOrder:(id)sender {
    
    
    if (![UserDefaults objectForKey:@"user"]) {
        UIStoryboard*story=[UIStoryboard storyboardWithName:@"Main" bundle:nil];
        LoginViewController*login=[story instantiateViewControllerWithIdentifier:@"LoginViewController"];
        [self.navigationController pushViewController:login animated:YES];
        
    }else{
        //有默认地址的情况，直接提交订单
        if (havePlace) {
            
            [self makeAOrder];
        }
        //没有默认地址的情况，设置默认地址
        else{
            self.hidesBottomBarWhenPushed = YES;
            UIStoryboard*story=[UIStoryboard storyboardWithName:@"Main" bundle:nil];
            LocationListViewController*login=[story instantiateViewControllerWithIdentifier:@"LocationListViewController"];
            [self.navigationController pushViewController:login animated:YES];
        }
    }
}

-(void)makeAOrder{

//    buycarid	数字	商品 	是
//    address	数字	收货地址 	是
//    price	数字	商品单价	是
//    discount_price	数字	优惠单价	是
//    shipping_id	数字	物流 	是
//    shipping_base_fee	数字	运费	是
//    total	数字	总金额(单价*数量+运费)	是
//    content	字符串	物品名	是
//    quantity	数字	数量	是
//    usernote	字符串	用户描述	否
//    delivertime	字符串	发货时间	否

    
    NSString *goodsMessage = [UserDefaults objectForKey:@"goodsMessage" ];
    
//    goodsDic[@""]
    
    [[AppAPIClient sharedClient] POST:@"Shop/CreateOrder" parameters:@{@"buycarid": goodsDic[@"pid"],@"address":[NSString stringWithFormat:@"%ld",(long)placeId],@"price":goodsDic[@"price"],@"discount_price":goodsDic[@"discount_price"],@"shipping_id":goodsDic[@"shipping_id"],@"shipping_base_fee":goodsDic[@"shipping_base_fee"],@"total":[NSString stringWithFormat:@"%ld",(long)totalMoney],@"content":goodsDic[@"name"],@"quantity":[NSString stringWithFormat:@"%ld", (long)intGoodsNumber],@"usernote":goodsMessage,@"delivertime":@""} success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if ([responseObject [@"code"] integerValue] == 1) {
            [SVProgressHUD showSuccessWithStatus:@"提交订单成功"];
            NSDictionary *goodsPayData = responseObject[@"data"];
            [UserDefaults setObject:goodsPayData forKey:@"goodsPayData"];
            
            //这里要push到一个新的界面
            UIStoryboard*story=[UIStoryboard storyboardWithName:@"Main" bundle:nil];
            PayTheVIPViewController*web=[story instantiateViewControllerWithIdentifier:@"PayTheVIPViewController"];
            
            [self.navigationController pushViewController:web animated:YES];
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [SVProgressHUD showErrorWithStatus:@"提交订单失败"];
        NSLog(@"Log:%@",operation.responseString);
    }];
}


- (IBAction)setPlace:(id)sender {
    
    if (![UserDefaults objectForKey:@"user"]) {
        UIStoryboard*story=[UIStoryboard storyboardWithName:@"Main" bundle:nil];
        LoginViewController*login=[story instantiateViewControllerWithIdentifier:@"LoginViewController"];
        [self.navigationController pushViewController:login animated:YES];
        
    }else{
        self.hidesBottomBarWhenPushed = YES;
        UIStoryboard*story=[UIStoryboard storyboardWithName:@"Main" bundle:nil];
        LocationListViewController*login=[story instantiateViewControllerWithIdentifier:@"LocationListViewController"];
        [self.navigationController pushViewController:login animated:YES];
    }
    
}




@end
